const querystring = require('querystring')
const handleBlogRouter = require('./src/router/blog')
const handleUserRouter = require('./src/router/user')
const { access } = require('./src/utils/log')
const { set, get } = require('./src/db/redis')

// session 数据
// const SESSION_DATA = {}

// 设置 cookie 的过期时间
const setCookieExpires = () => {
  const d = new Date()
  d.setTime(d.getTime() + 24 * 60 * 60 * 1000)
  // d.setTime(d.getTime() + (60 * 1000))

  return d.toGMTString()
}

// 用于处理post 提交的数据
const getPostData = req => {
  const promise = new Promise((resolve, reject) => {
    if (req.method !== 'POST') {
      resolve({})
      return
    }
    if (req.headers['content-type'] !== 'application/json') {
      resolve({})
      return
    }

    let postData = ''
    req.on('data', chunk => {
      postData += chunk.toString()
    })
    req.on('end', () => {
      if (!postData) {
        resolve({})
        return
      }
      resolve(JSON.parse(postData))
    })
  })

  return promise
}

const serverHandle = (req, res) => {
  // 记录 access log
  access(`${req.method} -- ${req.url} -- ${req.headers['user-agent']} -- ${Date.now()}`)

  // 设置返回格式 JSON
  res.setHeader('Content-Type', 'application/json')

  // 获取path
  const url = req.url
  req.path = url.split('?')[0]

  // 解析 query
  req.query = querystring.parse(url.split('?')[1])

  // 解析 cookie
  req.cookie = {}
  const cookieStr = req.headers.cookie || '' // k1=v1;k2=v2
  cookieStr.split(';').forEach(item => {
    if (!item) {
      return
    }
    const arr = item.split('=')
    const key = arr[0].trim()
    const val = arr[1].trim()
    req.cookie[key] = val
  })
  // console.log(req.cookie)

  // 解析 session
  // let needSetCookie = false
  // let userId = req.cookie.userid
  // // 首次登陆，cookie中没有userId，随机起一个userId，SESSION_DATA上此userId挂在为空
  // // 去数据库查询登陆，通过设置req.session设置SESSION_DATA[userId]
  // // 将userId返回给浏览器
  // // 登陆完以后再进来 因为cookie中已经有userId了,所以直接去SESSION_DATA去找对应的userId，拿用户信息
  // if (userId) {
  //   if (!SESSION_DATA[userId]) {
  //     SESSION_DATA[userId] = {}
  //   }
  // } else {
  //   needSetCookie = true
  //   userId = `${Date.now()}_${Math.random()}`
  //   SESSION_DATA[userId] = {}
  // }
  // req.session = SESSION_DATA[userId]

  // 解析 session (使用redis)
  let needSetCookie = false
  let userId = req.cookie.userid
  if (!userId) {
    needSetCookie = true
    userId = `${Date.now()}_${Math.random()}`
    // 初始化 redis 中的 session 值
    set(userId, {})
  }
  // 获取 session
  req.sessionId = userId
  get(userId).then(sessionData => {
    if (sessionData === null) {
      // 初始化 redis 中的 session 值
      set(req.sesionId, {})
      // 设置 session
      req.session = {}
    } else {
      req.session = sessionData
    }

    if (req.method === 'POST') {
      let postData = ''
      req.on('data', chunk => {
        postData += chunk.toString()
      })

      req.on('end', () => {
        console.log(postData)
        req.body = querystring.parse(postData)
  
        console.log(req.body)
        const blogResult = handleBlogRouter(req, res)
        if (blogResult) {
          blogResult.then(data => {
            if (needSetCookie) {
              res.setHeader(
                'Set-Cookie',
                `userid=${userId}; path=/; httpOnly; expires=${setCookieExpires()}`
              )
            }
            res.end(JSON.stringify(data))
          })
          return
        }

        // 处理 user 路由
        const userResult = handleUserRouter(req, res)
        if (userResult) {
          userResult.then(data => {
            if (needSetCookie) {
              res.setHeader(
                'Set-Cookie',
                `userid=${userId}; path=/; httpOnly; expires=${setCookieExpires()}`
              )
            }
            res.end(JSON.stringify(data))
          })
          return
        }

        // 未命中路由, 返回 404
        res.writeHead(404, { 'Content-Type': 'text/plain' })
        res.write('404 Not Found')
        res.end()
      })
      return
    }

    const blogResult = handleBlogRouter(req, res)
    if (blogResult) {
      blogResult.then(data => {
        if (needSetCookie) {
          res.setHeader(
            'Set-Cookie',
            `userid=${userId}; path=/; httpOnly; expires=${setCookieExpires()}`
          )
        }
        res.end(JSON.stringify(data))
      })
      return
    }

    // 处理 user 路由
    const userResult = handleUserRouter(req, res)
    if (userResult) {
      userResult.then(data => {
        if (needSetCookie) {
          res.setHeader(
            'Set-Cookie',
            `userid=${userId}; path=/; httpOnly; expires=${setCookieExpires()}`
          )
        }
        res.end(JSON.stringify(data))
      })
      return
    }

    // 未命中路由, 返回 404
    res.writeHead(404, { 'Content-Type': 'text/plain' })
    res.write('404 Not Found')
    res.end()
  })

  // 处理 post 提交过来的数据
  // getPostData(req).then(data => {
  //   req.body = data
  //   console.log(req.body)
  //   // 处理 blog 路由
  //   const blogResult = handleBlogRouter(req, res)
  //   if (blogResult) {
  //     blogResult.then(data => {
  //       res.end(JSON.stringify(data))
  //     })
  //     return
  //   }

  //   // 处理 user 路由
  //   const userData = handleUserRouter(req, res)
  //   if (userData) {
  //     res.end(JSON.stringify(userData))
  //     return
  //   }

  //   // 未命中路由, 返回 404
  //   res.writeHead(404, { 'Content-Type': 'text/plain' })
  //   res.write('404 Not Found')
  //   res.end()
  // })
}

module.exports = serverHandle
